package cn.sw.system.movies.agg.service.impl;

import cn.sw.common.database.domain.entity.Movies;
import cn.sw.common.database.domain.entity.MoviesContentDetails;
import cn.sw.common.utils.Mapper;
import cn.sw.system.movies.agg.domain.form.MoviesMoviesContentForm;
import cn.sw.system.movies.service.MoviesContentDetailsService;
import cn.sw.system.movies.service.MoviesService;
import com.alibaba.nacos.common.utils.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class AggMoviesMoviesContentServiceImpl {
    @Resource
    private MoviesService moviesService;
    @Resource
    private MoviesContentDetailsService contentDetailsService;


    @Transactional(rollbackFor = Exception.class)
    public boolean aggCreate(MoviesMoviesContentForm form) throws Exception {
        Assert.notNull(form, "参数不能为空");
        Assert.notNull(form.getMoviesForm(), "电影信息不能为空");
        Assert.notEmpty(form.getMoviesContentDetailsForm(), "电影内容不能为空");

        // 插入主表
        Movies movies = Mapper.map(form.getMoviesForm(), Movies.class);
        boolean saveMoviesBoolean = moviesService.save(movies);
        System.out.println(movies.getCreateTime());
        if (!saveMoviesBoolean) {
            return false;
        }

        if (CollectionUtils.isNotEmpty(form.getMoviesContentDetailsForm())) { //集合判空操作
            List<MoviesContentDetails> moviesContentDetails = Mapper.mapList(form.getMoviesContentDetailsForm(), MoviesContentDetails.class);
            for (MoviesContentDetails detail : moviesContentDetails) {
                detail.setMoviesId(movies.getId());
            }
            boolean saveAll = contentDetailsService.saveBatch(moviesContentDetails);
            if (!saveAll) {
                return false;
            }
        }

        return true;
    }

}
